package org.example.testdemo.interceptor;


import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.testdemo.tool.ApiResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class LoginBlocking implements HandlerInterceptor {

	/**
	 * 访问控制器方法前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		try {
			//拿出session
			HttpSession session=request.getSession();
			//判断是否登录成功
			Object userId = session.getAttribute("userId");
			if(userId==null){
				response.getWriter().write(JSONObject.toJSONString(ApiResponse.fail(403,"未获取权限")));
				return false;
			}
			return true;
		}catch (Exception e){
			response.getWriter().write(JSONObject.toJSONString(ApiResponse.error()));
			return false;
		}
	}

	/**
	 * 访问控制器方法后执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * postHandle方法执行完成后执行，一般用于释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
